package com.penton.util.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自定义TextView,TextView自带了该功能,但功能有限,最重要的是TextView失去焦点的情况下走马灯效果会暂停！
 * startMove()启动跑马灯
 * @author pengjianbo <pengjianbosoft@gmail.com>
 * 
 */
public class MarqueeView extends TextView implements Runnable {

	private Text text;

	public MarqueeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		text = new Text("走马灯效果演示...", 0, 20, 5);
	}

	public void startMove() {
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 1.刷新
				postInvalidate();
				// 2.睡眠
				Thread.sleep(200L);
				// 3.移動
				text.move();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// 背景色
		canvas.drawColor(Color.WHITE);
		// 绘制文字
		text.draw(canvas);
	}

	class Text {
		private Paint paint;
		private String content;// 文字内容
		private float x;// x坐标
		private float y;// y坐标
		private float stepX;// 移动步长
		private float contentWidth;// 文字宽度

		public Text(String content, float x, float y, float stepX) {
			this.content = content;
			this.x = x;
			this.y = y;
			this.stepX = stepX;
			// 画笔参数设置
			paint = new Paint();
			paint.setColor(Color.RED);
			paint.setTextSize(20f);
			this.contentWidth = paint.measureText(content);
		}

		public void move() {
			x -= stepX;
			if (x < -contentWidth)// 移出屏幕后,从右侧进入
				x = 320;// 屏幕宽度,真实情况下应该动态获取,不能写死
		}

		public void draw(Canvas canvas) {
			canvas.drawText(content, x, y, paint);
		}
	}
}
